<template>
	<div class="table-demo-container layout-padding">
		<div class="table-demo-padding layout-padding-view layout-padding-auto">
			<TableSearch :search="state.tableData.search" @search="onSearch" @addRow="onTableEditRow"
				@importFile="importFile" @activationCard="activationCard" />
			<div style="display: flex; overflow: hidden;position: relative;flex: 1;">
				<div class="menu-left" >
			<div>
				<fast-tree-component :treeData="treeState.treeData" :treeProps="treeProps"
						@selectedCode="selectedCode"></fast-tree-component>
			</div>
					<div class="btns">
						<SvgIcon style="cursor: pointer;" name="iconfont icon-yunshangchuan_o" :size="22" title="导入部门" @click="importOrg" />
						<SvgIcon style="margin-left: 10px;;cursor: pointer;" name="iconfont icon-yunxiazai_o" :size="22"
							title="导出部门" @click="exportOrg" />
					</div>
				</div>

				<Table ref="tableRef" v-bind="state.tableData" class="table-demo" @delRow="onTableDelRow"
					@editRow="onTableEditRow" @pageChange="onTablePageChange" @sortHeader="onSortHeader" />
			</div>

		</div>
		<editComponent ref="dialogRef" @refresh="getTableData()" />
		<importComponent ref="importdialogRef" @refresh="getTableData()" />
		<importOrgComponent ref="importOrgDialogRef" @refresh="getTreeMenus()" />
		<activationCardDialog ref="activationCardDialogRef" @refresh="getTreeMenus()" />
	</div>
</template>

<script setup lang="ts">
import { defineAsyncComponent, reactive, ref, onMounted, provide } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { usePersonOrgTreeApi } from '/@/api/person/org';
import { usePersonEmployeeDeleteApi, usePersonEmployeeOrgExportApi, usePersonEmployeePageApi } from '/@/api/person/employee';
import { usePersonDictPageApi } from '/@/api/person/dict';
import { RefType } from '/@/types/global';
import { downloadFile } from '/@/utils/downloadFile';
import { readFile } from 'xlsx';
import table2excel from '/@/utils/myTable2excel.js';

const dialogRef = ref<RefType>();
const importOrgDialogRef = ref<RefType>();
const activationCardDialogRef = ref();
const editComponent = defineAsyncComponent(() => import('./editDialog.vue'));
const importComponent = defineAsyncComponent(() => import('./importDialog.vue'));
const importOrgComponent = defineAsyncComponent(() => import('./importOrgDialog.vue'));
const activationCardDialog = defineAsyncComponent(() => import('./activationCardDialog.vue'));
// 引入组件
const Table = defineAsyncComponent(() => import('./table.vue'));
const TableSearch = defineAsyncComponent(() => import('/@/views/person/employee/search.vue'));
const fastTreeComponent = defineAsyncComponent(() => import('/@/views/person/employee/fastTree/index.vue'));

const treeProps = {
	label: 'name',
	key: 'code',
	children: 'children'
}

// 定义变量内容
const tableRef = ref<RefType>();
const importdialogRef = ref<RefType>();
const state = reactive<any>({
	tableData: {
		// 列表数据（必传）
		data: [],
		// 表头内容（必传，注意格式）
		header: [
			{ key: 'code', colWidth: '', title: '工号', type: 'text', isCheck: true, sortable: true },
			{ key: 'name', colWidth: '', title: '姓名', type: 'text', isCheck: true, sortable: true },
			{ key: 'orgName', colWidth: '', title: '部门', type: 'text', isCheck: true, sortable: true },
			{ key: 'roleName', colWidth: '', title: '角色', type: 'text', isCheck: true, sortable: true },
		],
		ExportHeader: [
			{ key: 'code', title: '部门编号' },
			{ key: 'name', title: '部门名称' },
			{ key: 'parentCode', title: '父部门编号' },
			{ key: 'parentName', title: '父部门名称' },
		],
		dictConfig: [],
		// 配置项（必传）
		config: {
			total: 0, // 列表总数
			loading: true, // loading 加载
			isBorder: true, // 是否显示表格边框
			isSerialNo: false, // 是否显示表格序号
			isSelection: true, // 是否显示表格多选
			isOperate: true, // 是否显示表格操作栏
			baseUrl: import.meta.env.VITE_API_URL
		},
		// 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
		search: [
			{ label: '工号', prop: 'code', placeholder: '请输入工号', required: false, type: 'input', defaultValue: '' },
			{ label: '姓名', prop: 'name', placeholder: '请输入姓名', required: false, type: 'input', defaultValue: '' },
		],
		// 搜索参数（不用传，用于分页、搜索时传给后台的值，`getTableData` 中使用）
		param: {
			pageNum: 1,
			pageSize: 10,
		},
		// 打印标题
		printName: '打印示例',
	},
});
const treeState = reactive({
	treeData: []
})

// 初始化列表数据
const getTableData = () => {
	state.tableData.config.loading = true;
	state.tableData.data = [];
	usePersonEmployeePageApi(state.tableData.param).then(({ content }) => {
		state.tableData.data = content.list || []
		state.tableData.param.pageSize = content.pageSize
		state.tableData.param.pageNum = content.pageNum
		state.tableData.config.total = content.total
	})
	// 获取字典
	usePersonDictPageApi({ pageNum: 1, pageSize: 20, isShow: 1 }).then(({ content }) => {
		state.tableData.dictConfig = content.list || []
	})
	// 数据总数（模拟，真实从接口取）
	state.tableData.config.loading = false;
};

// 主页面获取树状菜单
const getTreeMenus = () => {
	usePersonOrgTreeApi("").then(({ content }) => {
		treeState.treeData = content
	})
}
provide('getTreeMenus', getTreeMenus)

// 勾选关联查询table
const selectedCode = (data: any) => {
	state.tableData.param = Object.assign({}, state.tableData.param, { orgCodes: data });
	getTableData()
}

// 搜索点击时表单回调
const onSearch = (data: EmptyObjectType) => {
	state.tableData.param = Object.assign({}, state.tableData.param, { ...data });
	// tableRef.value.pageReset();
	getTableData()
};

//临时卡激活
const activationCard = () => {
	console.log('临时卡激活')
	activationCardDialogRef.value.openDialog();
};

//导入
const importFile = () => {
	importdialogRef.value.openDialog();
};

//导入部门
const importOrg = () => {
	importOrgDialogRef.value.openDialog();
};

// 导出部门
const exportOrg = () => {
	ElMessageBox.confirm(`此操作将导出部门表，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(() => {
		// axios.post(`${state.tableData.config.baseUrl}/v0/attend/daily/exportCountEmployee`,{})
		usePersonEmployeeOrgExportApi().then(({ content }) => {
			table2excel(state.tableData.ExportHeader, content, `安防综合管理平台-部门表${new Date().toLocaleString()}`);
			ElMessage.success('导出成功！');
		})
	});
};

// 删除当前项回调
const onTableDelRow = (row: EmptyObjectType) => {
	ElMessageBox.prompt('请输入删除原因', '提示', {
		confirmButtonText: '是',
		cancelButtonText: '否',
		type: 'success',
	}).then(({ value }) => {
		console.log(value);
		usePersonEmployeeDeleteApi(row.code, value).then(() => {
			ElMessage.success(`删除${row.name}成功！`);
			getTableData();
		})
	});

};
// 编辑当前项回调
const onTableEditRow = (row: EmptyObjectType) => {
	if (row) {
		dialogRef.value.openDialog(row.code);
	} else {
		dialogRef.value.openDialog();
	}
};
// 分页改变时回调
const onTablePageChange = (page: TableDemoPageType) => {
	state.tableData.param.pageNum = page.pageNum;
	state.tableData.param.pageSize = page.pageSize;
	getTableData();
};
// 拖动显示列排序回调
const onSortHeader = (data: TableHeaderType[]) => {
	state.tableData.header = data;
};
// 页面加载时
onMounted(() => {
	getTableData();
	getTreeMenus();
});
</script>

<style scoped lang="scss">
.table-demo-container {
	.table-demo-padding {
		padding: 15px;

		.table-demo {
			flex: 1;
			overflow: hidden;
		}
	}
}

.menu-left {
	height: calc(100% - 50px);
	margin-right: 15px;
	overflow-y: auto;
	padding: 0 5px 0 0;
	width: 320px;
	display: flex;
	flex-direction: column;
	justify-content: space-between;

}

.btns {
	position: absolute;
	bottom: 5px;
	padding-left: 260px;
	display: flex;
}
</style>
